<template>
    <Card dis-hover :bordered="false">
        <Button class="ivu-mb-16" type="primary" @click="handleOpenDrawer(false)" v-hasC="{
                          name: 'v1-automation-push-create-push',
                          flag: 'v1/automation/push/create-push',
                      }">新增</Button>
        <Table ref="table"  :columns='columns' :loading='loading' :data='data'>
            <template slot="action" slot-scope="{row}">
                <a @click="handleOpenDrawer(row)" v-hasC="{
                          name: 'v1-automation-push-update-push',
                          flag: 'v1/automation/push/update-push',
                      }">编辑</a>
                <Divider type="vertical" v-hasCC="[
                          { name: 'v1-automation-push-update-push', flag: 'v1/automation/push/update-push' },
                          { name: 'v1-automation-push-delete-push2', flag: 'v1/automation/push/delete-push' }
                      ]"/>
                <a @click="deletePush(row)" v-hasC="{
                          name: 'v1-automation-push-delete-push2',
                          flag: 'v1/automation/push/delete-push',
                      }">删除</a>
            </template>
            <template slot="footer">
                <Page
                    show-total show-elevator
                    show-sizer transfer
                    :total="total"
                    :current.sync="params.page"
                    :page-size="params.pageSize"
                    :page-size-opts="pageOpts"
                    @on-change="changepage"
                    @on-page-size-change="changepageSize"
                    style="text-align: center;"
                />
            </template>
        </Table>
        <Modal v-model="modal" width="750" :title="edit ? `编辑` : `新增`" :mask-closable="false"
            @on-cancel="handleDrawerCancel(modalname)">
            <Form :ref="modalname" :model="formItem" :rules="createRules" :label-width="100">
                <FormItem label="数据类型：" required>
                    <RadioGroup v-model="formItem.date_type">
                        <Radio :label="2">部门</Radio>
                        <Radio :label="5">渠道</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem v-if="formItem.date_type === 2" label="部门" prop="relation_id">
                    <Select multiple v-model="formItem.relation_id" :max-tag-count="3" placeholder="请选择部门" filterable>
                        <Option v-for="item in departmentList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                    </Select>
                </FormItem>
                <template v-if="formItem.date_type === 5">
                    <Row :gutter="8"  v-for="(items, allIndex) in formItem.sourceChannel"  :key="allIndex">
                        <Col>
                            <FormItem label="渠道：" :prop=" 'sourceChannel.' + allIndex + '.relation_id' " :rules="{ required: true, message: '请选择一级渠道', trigger: 'change' }">
                                <Select v-width="130" v-model="items.relation_id" placeholder="请选择一级渠道" filterable @on-change="changesource">
                                    <Option v-for="item in sourceChannelList" :value="item.value" :disabled="item.disabled&&items.relation_id!==item.value" :key="item.value">{{ item.label }}</Option>
                                </Select>
                            </FormItem>
                        </Col>
                        <Col v-if="items.relation_id" style="max-width:380px;min-width:280px">
                            <FormItem :label-width="0" :prop=" 'sourceChannel.' + allIndex + '.relation_ids' " :rules="{ required: true, type: 'array', message: '请选择二级渠道', trigger: 'change' }">
                                <Select multiple v-model="items.relation_ids" :max-tag-count="2" placeholder="请选择二级渠道" filterable>
                                    <Option v-for="item in items.sourceChannel" :value="item.value" :key="item.value">{{ item.label }}</Option>
                                </Select>
                            </FormItem>
                        </Col>
                        <Col>
                            <Button type="primary" v-if="allIndex === formItem.sourceChannel.length - 1" @click="addsourceChannel">
                                <Icon type="md-add"></Icon>
                            </Button>
                            <Button type="error" v-if="formItem.sourceChannel.length !== 1" :class="allIndex !== formItem.sourceChannel.length-1 ?'':'ivu-ml-8'" @click="deletesourceChannel(allIndex)">
                                <Icon type="md-close"></Icon>
                            </Button>
                        </Col>
                    </Row>
                </template>
                <FormItem label="钉钉token：" prop="dingtalk_id">
                    <Input type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" v-model="formItem.dingtalk_id" placeholder="请输入钉钉token" />
                </FormItem>
            </Form>
            <div slot="footer">
                <Button @click="handleDrawerCancel(modalname)">取消</Button>
                <Button type="primary" :loading="remarksloading" @click="handleSubmit(modalname)">确定</Button>
            </div>
        </Modal>
    </Card>
</template>

<script>
    import {
        automationpushbdflist,
        automationpushcreatepush,
        editAlreadyPush,
        automationPush
    } from '@/api/TApi/index.js';
    export default {
        data () {
            return {
                total: 0, //  分页总数
                pageOpts: [10, 20, 30, 50], //  分页每页数量
                params: { page: 1, pageSize: 10 }, //  请求参数
                edit: true, //  编辑true,新增false
                loading: false, //  加载中
                modal: false, //  模态框开启属性
                remarksloading: false,
                modalname: 'formItem',
                columns: [
                    { title: '名称', key: 'type_name', tooltip: true, ellipsis: true, minWidth: 118 },
                    { title: '钉钉机器人token', key: 'dingtalk_id', tooltip: true, minWidth: 300 },
                    { title: '操作人', key: 'operation_name', width: 100 },
                    { title: '更新时间', key: 'updated_at', minWidth: 150 },
                    { title: '操作', slot: 'action', width: 150 }
                ], // 列表表头
                data: [], // 列表数据
                formItem: {
                    id: '',
                    ding_type: 4,
                    date_type: 2,
                    dingtalk_id: '',
                    sourceChannel: [
                        { relation_id: '', relation_ids: [], sourceChannel: [] }
                    ],
                    relation_id: []
                },
                departmentList: [],
                sourceChannelList: [],
                // 模态框数据
                createRules: {
                    dingtalk_id: [{ trigger: 'blur', pattern: /^https:\/\//, required: true, message: '请正确输入包含https的钉钉token' }],
                    relation_id: [{ required: true, type: 'array', message: '请选择部门', trigger: 'change' }]
                } // 模态框验证规则
            };
        },
        /* 函数方法集合 */
        methods: {
            /* @函数功能: 初始化 */
            initial () {
                this.askData();
            },
            /* @函数功能: 请求数据 */
            askData () {
                automationpushbdflist(this.params).then(res => {
                    this.data = res.list.list
                    this.total = res.list.total
                    if (+this.departmentList.length === 0) this.departmentList = res.department
                    if (+this.sourceChannelList.length === 0) this.sourceChannelList = res.sourceChannel
                })
            },
            changepageSize (e) {
                this.params.page = 1;
                this.params.pageSize = e;
                this.askData();
            },
            changepage (e) {
                this.params.page = e;
                this.askData();
            },
            handleOpenDrawer (row) {
                this.formItem = {
                    id: '',
                    ding_type: 4,
                    date_type: 2,
                    dingtalk_id: '',
                    sourceChannel: [{ relation_id: '', relation_ids: [], sourceChannel: [] }],
                    relation_id: []
                }
                if (row) {
                    this.formItem.id = row.id
                    this.formItem.date_type = +row.date_type
                    this.formItem.dingtalk_id = row.dingtalk_id
                    if (+row.date_type === 5) {
                        this.formItem.sourceChannel = []
                        row.type_name_obj.forEach(item => {
                            let sourceChannel = []
                            this.sourceChannelList.forEach(items => {
                                if (item.id === items.value) {
                                    sourceChannel = items.children
                                }
                            });
                            this.formItem.sourceChannel.push({
                                relation_id: item.id, relation_ids: item.children_list.split(','), sourceChannel: sourceChannel
                            })
                        })
                        this.changesourceChannel()
                    } else if (+row.date_type === 2) {
                        this.formItem.relation_id = row.relation_id.split(',')
                    }
                    this.edit = true
                } else {
                    this.edit = false
                }
                this.modal = true
            },
            handleDrawerCancel (name) {
                this.$refs[name].resetFields();
                this.modal = false
            },
            handleSubmit (name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        let list = []
                        if (this.formItem.date_type === 2) {
                            list = [{
                                relation_id: this.formItem.relation_id.join(','),
                                ding_type: this.formItem.ding_type,
                                dingtalk_id: this.formItem.dingtalk_id,
                                date_type: this.formItem.date_type
                            }]
                        } else {
                            this.formItem.sourceChannel.forEach(item => {
                                list.push({
                                    relation_id: `${item.relation_id},${item.relation_ids.join(',')}`,
                                    ding_type: this.formItem.ding_type,
                                    dingtalk_id: this.formItem.dingtalk_id,
                                    date_type: this.formItem.date_type
                                })
                            })
                        }
                        if (this.edit) {
                            editAlreadyPush({ id: this.formItem.id, ding_type: this.formItem.ding_type, date_type: this.formItem.date_type, list: list }).then(res => {
                                this.modal = false
                                this.askData()
                            })
                        } else {
                            automationpushcreatepush({ list: list }).then(res => {
                                this.modal = false
                                this.askData()
                            })
                        }
                    }
                })
            },
            changesource (e) {
                this.formItem.sourceChannel.forEach(item => {
                    if (e === item.relation_id) {
                        item.relation_ids = []
                        this.sourceChannelList.forEach(items => {
                            if (e === items.value) {
                                item.sourceChannel = items.children
                                items.children.forEach(iteming => {
                                    item.relation_ids.push(iteming.value)
                                })
                            }
                        });
                    }
                });

                this.changesourceChannel()
            },
            changesourceChannel () {
                this.sourceChannelList.forEach(item => {
                    item.disabled = false
                });
                this.sourceChannelList.forEach(item => {
                    this.formItem.sourceChannel.forEach(items => {
                        if (items.relation_id === item.value) item.disabled = true
                    });
                });
            },
            addsourceChannel () {
                this.formItem.sourceChannel.push({
                    relation_id: '',
                    relation_ids: [],
                    sourceChannel: []
                });
            },
            deletesourceChannel (index) {
                this.formItem.sourceChannel.splice(index, 1);
            },
            deletePush (row) {
                this.$Modal.confirm({
                    title: '删除提示',
                    content: '请确认是否删除白癜风数据提醒设置？',
                    loading: true,
                    onOk: () => {
                        automationPush({
                            id: row.id
                        })
                            .then((res) => {
                                this.$Message.success('删除成功');
                                this.$Modal.remove();
                                this.askData();
                            })
                            .catch(() => {
                                this.$Modal.remove();
                        });
                    }
                });
            }
        },
        /* 挂载完成能访问DOM元素 */
        mounted () {
            this.initial();
        }
    };
</script>

<style lang="less" scoped></style>
